# -*- coding: utf-8 -*-

import psutil
import time
from pprint import pprint

# 定义一个获取系统信息的类

class Minitor(object):
    # 用于单位转换方法
    def bytes_to_gb(self, data, key=""):
        if key == "percent":
            return data
        return round(data / (1024 ** 3), 2)

    # 获取cpu
    def cpu(self):
        # 平均，单独，物理，逻辑
        data = dict(
            percent_avg=psutil.cpu_percent(interval=0, percpu=False),
            percent_per=psutil.cpu_percent(interval=0, percpu=True),
            num_p=psutil.cpu_count(logical=False),
            num_l=psutil.cpu_count(logical=True)
        )
        return data

    # 获取内存信息
    def men(self):
        info = psutil.virtual_memory()
        data = dict(
            total=self.bytes_to_gb(info.total),
            used=self.bytes_to_gb(info.used),
            free=self.bytes_to_gb(info.free),
            percent=info.percent
        )
        return data

    def swap(self):
        # 交换分区、文件
        info = psutil.swap_memory()
        data = dict(
            total=self.bytes_to_gb(info.total),
            free=self.bytes_to_gb(info.free),
            used=self.bytes_to_gb(info.used),
            percent=info.percent
        )
        return data

    #$ 获取磁盘信息
    def disk(self):
        info = psutil.disk_partitions()
        # 列表推导式
        data = [
            dict(
                device=v.device,
                mountpoint=v.mountpoint,
                fstype=v.fstype,
                opts=v.opts,
                used={
                    k: self.bytes_to_gb(v, k)
                    for k, v in psutil.disk_usage(v.mountpoint)._asdict().items()
                }

            )
            for v in info
        ]
        return data


if __name__ == '__main__':
    m = Minitor()
    # for v in range(1, 11):
    #     print(m.cpu())
    #     time.sleep(1)
    # print(m.men())
    # print(m.swap())
    pprint(m.disk())




